package repository

import (
	"fmt"
	"log"

	_ "database/sql"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	global "minitool/backend/configure"
)

const (
	maxOpenConn = 1024
	maxIdleConn = 256

	mysqlName = "mysql"
)

var (
	db *gorm.DB
) 

func Init() {
	c := global.Config.Mysql
	mysqlSource := fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8&parseTime=True&loc=Local", c.User, c.Password, c.Server, c.Port, c.Name)

	var err error
	db, err = gorm.Open(mysqlName, mysqlSource) 
	if err != nil {
		log.Fatal(err)
	}
	// defer db.Close()

	if err = db.DB().Ping(); err != nil {
		log.Fatal(err)
	}

	db.SingularTable(true)
	db.DB().SetMaxOpenConns(maxOpenConn)
	db.DB().SetMaxIdleConns(maxIdleConn)
}